package ${ormPackageName};
import java.sql.Connection;
import java.sql.SQLException;
import com.esdk.esdk;
import com.esdk.sql.BatchInsert;
import com.esdk.sql.BatchReplace;
import com.esdk.sql.Delete;
import com.esdk.sql.JDBCTemplate;
import com.esdk.sql.datasource.FileConnectionPool;
import com.esdk.sql.orm.ABRowSet;
import com.esdk.sql.orm.ConnectionUtils;
import com.esdk.sql.orm.ParentRow;
import com.esdk.sql.orm.SelectFactory;
import com.esdk.utils.CacheMap;

public class DF{
	private static CacheMap<Long,SelectFactory> selectFactoryMap=new CacheMap();
	
	static{
		ConnectionUtils.setDataSource(FileConnectionPool.getDataSource());
	}
	
	private static SelectFactory sf(){
		Long requestId=ConnectionUtils.getRequestId();
		SelectFactory sf=selectFactoryMap.get(requestId);
		if(sf==null){
			sf=new SelectFactory(ConnectionUtils.getConnection(requestId,ConnectionUtils.getRequestMethod()));
			selectFactoryMap.put(requestId,sf);
		}
		return sf;
	}
	
	private static Connection getConnection(){
		return ConnectionUtils.getConnection();
	}
	
	public static void closeCurrent(){
		Long requestId=ConnectionUtils.getRequestId();
		selectFactoryMap.remove(requestId);
		ConnectionUtils.closeConnection(requestId);
	}

	public static JDBCTemplate jdbc(String sql,Object... args) {
		return new JDBCTemplate(getConnection(),sql,args);
	}
	
	public static Delete delete(String tablename) throws SQLException {
		Delete delete=new Delete(tablename,getConnection());
		return delete;
	}
	
	public static <T extends ParentRow> void delete(ABRowSet<T> rs) throws Exception {
		if(!rs.isEmpty()) {
			Object md=rs.getFirstRow().getMetaData();
			String tablename=(String)esdk.reflect.getFieldValue(md,"TABLENAME");
			String pkfieldname=(String)esdk.reflect.getFieldValue(md,"PrimaryKey");
			Delete delete=new Delete(tablename,getConnection());
			delete.in(pkfieldname,rs.getNumbers(pkfieldname));
			delete.perform();
		}
	}
	
	public static BatchInsert batchInsert(String tablename) {
		return new BatchInsert(tablename,DF.getConnection());
	}
	
	public static BatchReplace batchReplace(String tablename) {
		return new BatchReplace(tablename,DF.getConnection());
	}
	
	public static boolean flush(ParentRow pr) throws SQLException {
		pr.setConnection(getConnection());
		return pr.flush();
	}

<#list daoList as item>
	/**${item.tableComment}*/
	public static ${item.ModelName}Select ${item.ModelName?uncap_first}Select() throws Exception{
	  return sf().createSelect(${item.ModelName}Select.class);
	}

	public static ${item.ModelName}Row ${item.ModelName?uncap_first}Row() throws Exception{
	  return sf().createRow(${item.ModelName}Row.class);
	}
	
	public static ${item.ModelName}Row ${item.ModelName?uncap_first}Row(Number pkid) throws Exception{
	  return sf().createRow(${item.ModelName}Row.class,pkid,true);
	}

	
</#list>
}
